/**
 * 版权所有(C)，上海海鼎信息工程股份有限公司，2008，所有权利保留。
 * 
 * 项目名：	rumba
 * 文件名：	Entry.java
 * 模块说明：	
 * 修改历史：
 * Feb 21, 2008 - linhui - 创建。
 */
package com.hd123.rumba.gwt.entry.client;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FocusWidget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.LoadListener;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.gwtext.client.core.DomConfig;
import com.gwtext.client.core.Ext;
import com.gwtext.client.core.ExtElement;
import com.gwtext.client.widgets.MessageBox;
import com.hd123.rumba.gwt.base.client.exception.ClientBizException;
import com.hd123.rumba.gwt.base.client.util.GWTUtil;
import com.hd123.rumba.gwt.cartridge.client.CartridgeService;
import com.hd123.rumba.gwt.cartridge.client.CartridgeViewPanel;
import com.hd123.rumba.gwt.cartridge.client.biz.QCartridge;
import com.hd123.rumba.gwt.cpnts.module.client.ModuleNavigator;
import com.hd123.rumba.gwt.widget.client.PasswordTextBoxE;
import com.hd123.rumba.gwt.widget.client.TextBoxE;

/**
 * 应用程序入口 | 入口
 * 
 * @author linhui
 * 
 */
public class Entry implements EntryPoint {
  private final static String PRODUCT = "Heading Rumba 2 - 海鼎商业应用框架";
  private final static String COPYRIGHT = "版权所有&copy; 2006-"
      + DateTimeFormat.getFormat("yyyy").format(new Date()) + " 上海海鼎信息工程股份有限公司 所有权利保留。";
  private final static String IMAGESOURCE = "images/login/rb_logo_coverEntry.gif";
  private TextBoxE txtLoginName;
  private PasswordTextBoxE txtPassword;
  private TextBox txtDomainCode;
  private TextBox txtToken;
  private TextBox btnLogin;
  private TextBox btnCancel;
  private boolean showToken;

  public void onModuleLoad() {
    loadTextBoxes();
    loadButtons();
    loadConfig();
    showToken = true;
  }

  private void loadTextBoxes() {
    txtLoginName = new TextBoxE();
    txtLoginName.setStyleName("login_input");
    RootPanel.get("loginSlot").add(txtLoginName);

    txtPassword = new PasswordTextBoxE();
    txtPassword.setStyleName("login_input");
    RootPanel.get("passwordSlot").add(txtPassword);

    txtDomainCode = new TextBox();
    txtDomainCode.setTitle("DomainCode");
    txtDomainCode.setStyleName("login_input");
    txtDomainCode.addKeyboardListener(new MyKeyboardListener());
    RootPanel.get("domainCodeSlot").add(txtDomainCode);

    txtToken = new TextBox();
    txtToken.setTitle("Token");
    txtToken.setStyleName("login_input");
    txtToken.addKeyboardListener(new MyKeyboardListener());
    RootPanel.get("tokenSlot").add(txtToken);
  }

  private class MyKeyboardListener implements KeyboardListener {
    public void onKeyDown(Widget sender, char keyCode, int modifiers) {
      handleKey(sender, keyCode, modifiers);
    }

    public void onKeyPress(Widget sender, char keyCode, int modifiers) {
      handleKey(sender, keyCode, modifiers);
    }

    public void onKeyUp(Widget sender, char keyCode, int modifiers) {
      // handleKey(sender, keyCode, modifiers);
    }

    private void handleKey(Widget sender, char keyCode, int modifiers) {
      if (keyCode == KeyCodes.KEY_ENTER && sender instanceof FocusWidget) {
        if (sender.equals(txtLoginName))
          txtPassword.setFocus(true);
        else if (sender.equals(txtPassword))
          txtDomainCode.setFocus(true);
        else if (sender.equals(txtDomainCode)) {
          if (showToken == false)
            doLogin();
          else
            txtToken.setFocus(true);
        } else if (sender.equals(txtToken))
          doLogin();
      }
    }
  }

  private void loadButtons() {
    btnLogin = new TextBox();
    btnLogin.setStyleName("logon_button");
    btnLogin.setText(" 登 录 ");
    DOM.setElementAttribute(btnLogin.getElement(), "type", "image");
    DOM.setElementAttribute(btnLogin.getElement(), "src", "images/login/login_button.jpg");
    btnLogin.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        //String loginName = txtLoginName.getText().trim();
        //MessageBox.alert("message", "loginName=" + loginName);
        doLogin();
      }
    });
    btnLogin.addKeyboardListener(new KeyboardListener() {
      public void onKeyDown(Widget sender, char keyCode, int modifiers) {
        if (keyCode == KEY_ENTER)
          doLogin();
      }

      public void onKeyPress(Widget sender, char keyCode, int modifiers) {
      }

      public void onKeyUp(Widget sender, char keyCode, int modifiers) {
      }
    });
    RootPanel.get("loginButtonSlot").add(btnLogin);

    btnCancel = new TextBox();
    btnCancel.setStyleName("logon_button");
    btnCancel.setText(" 重 置 ");
    DOM.setElementAttribute(btnCancel.getElement(), "type", "image");
    DOM.setElementAttribute(btnCancel.getElement(), "src", "images/login/cancel_button.jpg");
    btnCancel.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        clearInput();
      }
    });
    btnCancel.addKeyboardListener(new KeyboardListener() {
      public void onKeyDown(Widget sender, char keyCode, int modifiers) {
        if (keyCode == KEY_ENTER)
          clearInput();
      }

      public void onKeyPress(Widget sender, char keyCode, int modifiers) {
      }

      public void onKeyUp(Widget sender, char keyCode, int modifiers) {
      }
    });
    RootPanel.get("cancelButtonSlot").add(btnCancel);
  }

  private void clearInput() {
    txtLoginName.setText("");
    txtPassword.setText("");
    txtDomainCode.setText("");
    txtToken.setText("");
    txtLoginName.selectAll();
    txtLoginName.setFocus(true);
  }

  /**
   * 加载令牌配置信息
   * 
   */
  private void loadConfig() {
    EntryService.Locator.getService().loadConfig(new AsyncCallback() {
      public void onFailure(Throwable caught) {
        String message = "";
        if (caught.getMessage().indexOf("]") > 0
            && caught.getMessage().indexOf("]") != caught.getMessage().length() - 1)
          message = caught.getMessage().substring(caught.getMessage().indexOf("]") + 1);
        MessageBox.alert(Window.getTitle(), message);
      }

      public void onSuccess(Object result) {
        assert result instanceof Map;
        Map config = (Map) result;
        Boolean tokenLogin = (Boolean) config.get("tokenLogin");
        if (tokenLogin.booleanValue() == false) {
          RootPanel.get("trToken").setVisible(false);
          showToken = false;
        }

        RootPanel.get("mainTable").setVisible(true);
        txtLoginName.setFocus(true);

        loadCoverCartridge();

        loadAllCartridges();
      }
    });
  }

  private void loadCoverCartridge() {
    CartridgeService.Locator.getService().getCoverCartridge(new AsyncCallback() {
      public void onFailure(Throwable caught) {
        MessageBox.alert(Window.getTitle(), caught.getMessage());
      }

      public void onSuccess(Object result) {
        String strProduct = PRODUCT;
        String strCopyright = COPYRIGHT;
        String strImageSource = IMAGESOURCE;

        if (result != null && result instanceof QCartridge) {
          QCartridge cover = (QCartridge) result;
          if (cover.getResources().get("logo_coverEntry") != null) {
            strImageSource = GWTUtil.getStaticContentURL((String) cover.getResources().get(
                "logo_coverEntry"));
          }
          strProduct = cover.getCaptionEN() + " " + cover.getCaption() + " 版本号："
              + cover.getVersion().toString();

          strCopyright = cover.getCopyright();
        }

        showCover(strImageSource);
        RootPanel.get("productNameSlot").add(new HTML(strProduct));
        RootPanel.get("copyrightSlot").add(new HTML(strCopyright));
      }

    });
  }

  private void showCover(String strImageSource) {
    final Image image = new Image();
    image.setUrl(strImageSource);
    image.addLoadListener(new LoadListener() {
      public void onError(Widget arg0) {
        image.setUrl(IMAGESOURCE);
      }

      public void onLoad(Widget arg0) {
      }
    });
    RootPanel.get("logoSlot").clear();
    RootPanel.get("logoSlot").add(image);
  }

  private void loadAllCartridges() {
    CartridgeService.Locator.getService().getAllCartridges(new AsyncCallback() {
      public void onFailure(Throwable caught) {
        String message = "";
        if (caught.getMessage().indexOf("]") > 0
            && caught.getMessage().indexOf("]") != caught.getMessage().length() - 1)
          message = caught.getMessage().substring(caught.getMessage().indexOf("]") + 1);
        MessageBox.alert(Window.getTitle(), message);
      }

      public void onSuccess(Object result) {
        if (result != null && result instanceof List) {
          CartridgeViewPanel pnlCartridge = new CartridgeViewPanel();
          pnlCartridge.setCartridges((List) result);
          pnlCartridge.setId("cartridges");
          pnlCartridge.setWidth(350);

          RootPanel.get("cartridgeList").clear();
          RootPanel.get("cartridgeList").add(pnlCartridge.showCartridges());
        }
      }
    });
  }

  private boolean isLogining = false;

  private void doLogin() {
    if (isLogining)
      return;
    
    String loginName = txtLoginName.getText().trim();
    String password = txtPassword.getText();
    String domainCode = txtDomainCode.getText().trim();
    String tokenValue = txtToken.getText().trim();
    
    if (!validateParameters(loginName, password, domainCode)) {
      return;
    }
    
    final ExtElement element = Ext.get("mainTable");
    Element wrap = element.wrap(new DomConfig("div"));
    final ExtElement maskedExtElement = new ExtElement(wrap);
    maskedExtElement.mask("正在登录系统……");
    isLogining = true;

    EntryService.Locator.getService().login(loginName, password, tokenValue, domainCode,
        new AsyncCallback() {
          public void onFailure(Throwable caught) {
            isLogining = false;
            maskedExtElement.unmask();
            String message = "";
            if (caught.getMessage().indexOf("]") > 0
                && caught.getMessage().indexOf("]") != caught.getMessage().length() - 1)
              message = caught.getMessage().substring(caught.getMessage().indexOf("]") + 1);
            MessageBox.alert(Window.getTitle(), message, new MessageBox.AlertCallback() {
              public void execute() {
                txtPassword.setText("");
                txtLoginName.selectAll();
                txtLoginName.setFocus(true);
              }
            });
          }

          public void onSuccess(Object result) {
            maskedExtElement.unmask();
            try {
              ModuleNavigator.navigate("entry.MainFrame/MainFrame.html");
            } catch (ClientBizException e) {
              MessageBox.alert(Window.getTitle(), "无法导航到指定页面。" + e.getMessage());
            }
            isLogining = false;
          }
        });
  }

  private boolean validateParameters(String loginName, String password, String domainCode) {
    if (loginName.equals("")) {
      MessageBox.alert(Window.getTitle(), "帐号不能为空！", new MessageBox.AlertCallback() {
        public void execute() {
          txtLoginName.setFocus(true);
        }
      });
      return false;
    }
    if (password.equals("")) {
      MessageBox.alert(Window.getTitle(), "密码不能为空！", new MessageBox.AlertCallback() {
        public void execute() {
          txtPassword.setFocus(true);
        }
      });
      return false;
    }
    if (domainCode.equals("")) {
      MessageBox.alert(Window.getTitle(), "组织不能为空！", new MessageBox.AlertCallback() {
        public void execute() {
          txtDomainCode.setFocus(true);
        }
      });
      return false;
    }
    return true;
  }
}
